package com.questionGenerator.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.questionGenerator.commom.constant.MessageConstant;
import com.questionGenerator.commom.constant.PasswordConstant;
import com.questionGenerator.commom.constant.StatusConstant;
import com.questionGenerator.dto.req.UserLoginDTO;
import com.questionGenerator.dto.req.UserRegistryDTO;
import com.questionGenerator.mapper.UserMapper;
import com.questionGenerator.model.UserDO;
import com.questionGenerator.service.UserService;
import com.questionGenerator.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDate;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: usagi
 * @Date: 2024/04/09/16:50
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDO userlogin(UserLoginDTO userLoginDTO) throws Exception {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        UserDO user = userMapper.selectByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new Exception(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new Exception(MessageConstant.PASSWORD_ERROR);
        }

        if (user.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new Exception(MessageConstant.ACCOUNT_LOCKED);
        }

        user.setLoginDate(LocalDate.now().toString());

        //3、返回实体对象
        return user;
    }

    @Override
    public UserVO save(UserRegistryDTO userRegistryDTO) {
        UserDO user = new UserDO();

        // 拷贝属性
        BeanUtils.copyProperties(userRegistryDTO,user);

        user.setId(null);

        //设置账号的状态，默认正常状态 0表示正常，1表示冻结
        user.setStatus(StatusConstant.ENABLE);

        if(user.getPassword() == null){
            //设置密码，默认密码123456
            user.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        }else{
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }

        userMapper.insert(user);
        return BeanUtil.copyProperties(user,UserVO.class);
    }
}
